package com.wms.ymcc.mq;

import com.alibaba.fastjson.JSONObject;
import com.wms.ymcc.constant.ValidationConstants;
import com.wms.ymcc.domain.MessageEmail;
import com.wms.ymcc.dto.MessageEmailDto;
import com.wms.ymcc.dto.User2EmailDto;
import com.wms.ymcc.exception.GlobalBaseException;
import com.wms.ymcc.service.IMessageEmailService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @author : 阿盛哟
 * @description : 站内消息
 * @createDate : 2025/6/20 20:28
 */
@RocketMQMessageListener(topic = ValidationConstants.ROCKETMQ_TOPIC_PUBLISH,
        selectorExpression = ValidationConstants.ROCKETMQ_TAGS_EMAIL,
        consumerGroup = "service-common-consumer-email")
@Service
@Slf4j
public class MQConsumerEmailService implements RocketMQListener<MessageExt> {


    @Autowired
    private IMessageEmailService messageEmailService;

    /**
     * 消费
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1. 获取到消息
        try {
            String jsonStrMessage = new String(messageExt.getBody(), "UTF-8");
            MessageEmailDto messageEmailDto = JSONObject.parseObject(jsonStrMessage, MessageEmailDto.class);
            // 2. 存到 t_message_email
            List<User2EmailDto> user2EmailDtos = messageEmailDto.getUser2EmailDtos();

            user2EmailDtos.stream().forEach(ue -> {
                MessageEmail messageEmail = new MessageEmail();
                BeanUtils.copyProperties(messageEmailDto,messageEmail);
                messageEmail.setSendTime(new Date());
                messageEmail.setUserId(ue.getUserId());
                messageEmail.setEmail(ue.getEmail());
                messageEmailService.insert(messageEmail);
            });

            // 发送邮件。。。。。。。  略
            log.info("邮件推送消息消费结果成功");

        } catch (UnsupportedEncodingException e) {
            throw new GlobalBaseException("邮件推送消息消费失败");
        }


    }
}